var websocket;
//连接信息
function start_print(jsonInfo) {
    var wsaddr = 'ws://127.0.0.1:1920';
	StartWebSocket(wsaddr,jsonInfo);
}

//断开链接调此方法
function closesocket() {
	websocket.close();
}

function StartWebSocket(wsUri,jsonInfo) {
    websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) {onOpen(evt)};
    websocket.onclose = function(evt) { onClose(evt) };
    websocket.onmessage = function(evt) { onMessage(evt,jsonInfo) };
    websocket.onerror = function(evt) { onError(evt) };
}

function onOpen(evt) {
    console.log('连接成功，现在你可以发送信息啦');
}

function onClose(evt) {
    console.log('websocket连接已断开');
    websocket.close();
}

function onMessage(evt,jsonInfo) {
    doSend(jsonInfo)
}

function onError() {
    layer.msg('发生错误,请检测打印软件是否启动', {time: 5000});
    return false;
}

//获取打印数据，调起打印界面
function doSend(jsonInfo){
    $.post("/xiaochengxu/api/order.php?action=printTpl",{}, function(res) {
        if(res.code){
            layer.msg(res.message, {time: 5000});
            return false;
        }
        var dataInfo=JSON.parse(jsonInfo);
        var data_val={
            "商铺名称":dataInfo.username,
            "备注":'备注：'+dataInfo.remarks,
            "包装费":'包装费：'+dataInfo.pack_fee+'元',
            "配送费":'配送费：'+dataInfo.delivery_fee+'元',
            "总计":'总计：'+dataInfo.Totalprice+'元',
            "送货地点":'送货地点：'+dataInfo.add_place,
            "联系人":'联系人：'+dataInfo.add_link,
            "联系电话":'联系电话：'+dataInfo.add_mobile,
            "订餐时间":'订餐时间：'+dataInfo.time,
            "订单编号":'订单编号：'+dataInfo.ordernum,
        };
        var printInfo = {
            actions:'print',
            tpl_str:res.data,
            single_row:data_val,
            list_data:[
                {'table_name':'数据明细','rows':[JSON.parse(dataInfo.order_details)]}
            ]
        };
        var message=JSON.stringify(printInfo);
        if (typeof websocket==="undefined"){
            layer.msg('websocket还没有连接，或者连接失败，请检测', {time: 5000});
            return false;
        }
        if (websocket.readyState==3) {
            layer.msg('websocket已经关闭，请重新连接', {time: 5000});
            return false;
        }
        websocket.send(message);
    },'json');

}
